<template>
    <div class="handleDetail" >
        <div
        style="
                width: 100%;
            "
        >
            <div
                v-for="(elTab, index) in comArr[activeComNumber].label"
                :label="elTab"
                :key="elTab"
            >
                <div :id="comArr[activeComNumber].comName[index]"></div>
                <component
                    :ADDEDITLOOK="ADDEDITLOOK"
                    :isLook="isLook"
                    :nodeId="nodeId"
                    :busType="busType"
                    :flag="comArr[activeComNumber].flag"
                    :is="comArr[activeComNumber].comName[index]"
                    :ref="comArr[activeComNumber].comName[index]"
                ></component>
            </div>
        </div>
        <div class="btnList">
            <template v-if="isLook">
                <el-button
                    @click="btnFn('取消')"
                    size="small"
                >
                    取消
                </el-button>
            </template>
            <template v-else>
                <el-button
                    v-for="btnName in comArr[activeComNumber].btnArray"
                    @click="btnFn(btnName)"
                    :key="btnName"
                    size="small"
                    :disabled="btnName == '取消' ? false : btnLoading"
                    :type="btnName == '取消' ? '' : 'primary'"
                >
                    {{ btnName }}
                </el-button>
            </template>
        </div>
        <vxe-modal v-model="msgShow" width="60%"  @close="msgDialogFn">
                <template v-slot>
                    <div style="max-height: 100vh;overflow-y: auto;overflow-x: hidden;">
                        <div v-for="(msg,index) in messageDialog" :key="index">
                            {{ msg }}
                        </div>
                    </div>

                </template>
          </vxe-modal>

    </div>
</template>

  <script>
import com from '../com.json'
import lcxx from '../flowNew/StartProcess1.vue'
import sqxx from '../flowNew/applyInfo3.vue'
import fpxx from '../flowNew/InvoiceInfo2.vue'
import shgj from '../flowNew/ProcessTrack4.vue'
import jbxx from '../flowNew/BaseInfo5.vue'
import shyj from '../flowNew/ProcessAdvice6.vue'
import hzqrdsq from '../flowNew/redInvoiceApply7.vue' // 4.7 红字确认单申请
import hzqrdsp from '../flowNew/redInvoiceApprove8.vue' // 4.7 红字确认单审批
import hzqrdsqbc from '../flowNew/redInvoiceApplySave7.vue' // 4.7 单纯保存

import hzqrdqr from '../flowNew/redInvoiceConfig9.vue' // 4.8 红字确认单确认
import hzqrdqrsh from '../flowNew/redInvoiceConfig10.vue' // 4.8 红字确认单审核
import hzqrd from '../flowNew/redInvoiceResult11.vue'
// 4.1 发票匹配流水的 发票信息栏
import fpxxl from '../flowNew/invoiceInformation15.vue'
import fpxxlSP from '../flowNew/invoiceInformation16.vue'

import fpxxlCancel from '../flowNew/invoiceInformation30.vue'

import { saveOrSubmit ,handlingProcess, stopProcess} from '@/api/businessFlow.js'

import { beforeSaveValid } from './beforeSaveValids.js'
import { beforeInvoiceMatchFlow } from './beforeInvoiceMatchFlow.js'


export default {
    name: 'handleDetail',
    components: {
        fpxx,
        lcxx,
        sqxx,
        shgj,
        jbxx,
        shyj,
        hzqrdsq,
        hzqrdsqbc,
        hzqrdsp,
        hzqrd,
        fpxxl,
        fpxxlSP,
        fpxxlCancel,
        hzqrdqr,
        hzqrdqrsh,
    },
    props:{
        ADDEDITLOOK:{
            type: String,
            default:'EDIT'
        }
    },
    data() {
        return {
            btnLoading:false,
            messageDialog:[],
            msgShow:false,

            comArr: com,
            activeComNumber: '0',
            processId: '',
            nodeId: '',
            busId: '',
            busType: '',
            templateId: '',
            procInstId: '',
            isLook: false,
        }
    },
    created() {
        
        let cache = sessionStorage.getItem('handleDetailInfo')
        if (cache) {
            cache = JSON.parse(cache);
            this.activeComNumber = cache.activeComNumber
            this.processId  = cache.processId
            this.nodeId  = cache.nodeId // currentNodeName
            this.busId  = cache.busId
            this.busType  = cache.busType
            this.templateId  = cache.templateId
            this.procInstId  = cache.procInstId
            this.isLook  = cache.isLook
        }
    },
    methods: {
        msgDialogFn(){
            this.msgShow = false;
            this.messageDialog = []
        },
        // closeFather() {
        // },
        menuClick(dom) {
            document.getElementById(dom).scrollIntoView({ behavior: 'smooth' })
            return false
        },
        cancelConfirm(){
            if(this.ADDEDITLOOK == 'ADD' && !this.processId ){ // 新增分为 新增和启动流程,流程有id需要排除
                if(this.busType == 'FLOW_SGKP'){
                    return this.$confirm( `是否放弃本次新增开票申请？`,'确认').then(data=>{
                         this.closeDialog()
                    },err=>{
                    })
                }else if(this.busType == 'FLOW_HZQRDSQ'){
                    return this.$confirm( `是否放弃本次红字确认单申请？`,'确认').then(data=>{
                         this.closeDialog()
                    },err=>{
                    })
                }
                this.closeDialog()

            }else{
                this.closeDialog()
            }
        },
        hzValid(context){
            
            if(context.$refs&& context.$refs.hzqrdsq){
                let data = context.$refs.hzqrdsq[0].vmsApprovalHzqrdSimpleVo;
                if(data.lzfphm.length&& data.lzfphm.length<20 && (data.lzfpdm == '')){
                    this.$message.error('发票号码不足20位，发票代码不得为空！')
                    this.btnLoading = false
                    return false
                }
                 if(Array.isArray(data.vmsApprovalHzqrdItemVoList)&& data.vmsApprovalHzqrdItemVoList.length == 0){
                    this.$message.error('红冲发票明细不得为空！')
                    this.btnLoading = false
                    return false
                }
            }else if(context.$refs&& context.$refs.hzqrdsqbc){
                let data = context.$refs.hzqrdsqbc[0].vmsApprovalHzqrdSimpleVo;
                if(data.lzfphm.length&& data.lzfphm.length<20 && (data.lzfpdm == '')){
                    this.$message.error('发票号码不足20位，发票代码不得为空！')
                    this.btnLoading = false

                    return false
                }else if(data.vmsApprovalHzqrdItemVoList.length === 0){
                    this.$message.error('红冲发票明细不得为空！')
                    this.btnLoading = false
                    return false
                }
            }
            return true

        },
        async btnFn(name) {
            if (name !== '取消') {
                this.btnLoading = true
            }
            if (name === '取消') {
                this.cancelConfirm()
            } else  if (name === '保存') {
                if((this.busType === 'FLOW_HZQRDQR' || this.busType === 'FLOW_HZQRDSQ')&& !this.$store.state.invoice2.invoinceFormStart1.description ){
                    this.btnLoading = false;
                    return this.$message.error('请填写事项说明')
                }
                if(!this.hzValid(this))return; // 发票位数校验
                
                 let isContinue =  await  beforeSaveValid(this.busType,this)
                 isContinue&& await this.save();
            } else if (name === '提交') {
                if( (this.busType === 'FLOW_HZQRDQR' || this.busType === 'FLOW_HZQRDSQ')&& !this.$store.state.invoice2.invoinceFormStart1.description ){
                    this.btnLoading = false;
                    return this.$message.error('请填写事项说明')
                }
                if(!this.hzValid(this))return; // 发票位数校验

                let isContinue =  await  beforeSaveValid(this.busType,this)
                 isContinue&& await this.submit();
            } else if (name === '确认') {
              await  this.confirm()
            } else if (name === '终止') {
                await this.stop()
            } else if (name === '开票') {
                await this.invoice(this.INVOICERECEIVE.INVOICE);
            } else if (name === '下载授信额度') {
                await this.invoice(this.INVOICERECEIVE.DOWNLIMIT);
            } 
            else if (name === '退回授信额度') {
                await  this.invoice(this.INVOICERECEIVE.RETURNLIMIT)
            } 
            else if (name === '领用') {
                await this.invoice(this.INVOICERECEIVE.RECEIVE);
            }
            this.btnLoading = false;
        },
        async confirm(){ // 确认
            let obj = {
                "busId": this.busId,
                "handleResult": this.$store.state.invoice2.invoinceFormAdvice6.handleResult,
                "nextHandleUser": this.$store.state.invoice2.invoinceFormAdvice6.nextHandleUser,
                "remark": this.$store.state.invoice2.invoinceFormAdvice6.remark
            }
            if(await this.IsError()){
                this.btnLoading = false;
                if(!this.$store.state.fpxxlStore.matchAllowError.yxcyje){
                    return this.$message.error('请填写允许差异额')
                }else if(this.bigNumAbsoluteComparedTo(this.$store.state.fpxxlStore.matchAllowError.yxcyje,this.$store.state.fpxxlStore.matchAllowError.dqppcyje)){
                    return this.$message.error('差异值的绝对值必须小于等于允许的差异值的绝对值！请重新填写！')
            //   if (this.bigNumcomparedTo(r2, r1)) {
            //       this.$message.warning('第'+ (+i+1) +'条数据:本次扣除金额不能大于凭证合计金额')
            //     return
            //   }
                }
                if(!this.$store.state.fpxxlStore.matchAllowError.cyjesm ){
                    return this.$message.error('请填写差异金额说明')
                }

                return 
            }else{

            }


            if(this.$store.state.invoice2.invoinceFormAdvice6.handleResult == 3&&!this.$store.state.invoice2.invoinceFormAdvice6.remark){
                this.btnLoading = false;
                return this.$message.error('请填写事项说明')
            }

            if(!obj.remark && (this.busType === 'FLOW_HZQRDQR' || this.busType === 'FLOW_HZQRDSQ') && (obj.handleResult === 3)){
                this.btnLoading = false;
                return this.$message.error('请填写事项说明')
            }
            let { data, code, message } = await handlingProcess(
                obj
            )
            if(code ==200){
                this.$message.success(message || data)
                this.closeDialog()
            }
        },
        async invoice(ResultMsg){ // 开票
            let  obj = {
                    "handleResult": 1,
                    "busId": this.busId,
                }
            let { data, code, message } = await handlingProcess(
                obj
            )
            if(code == 200){
                let msg = '处理完毕，请在【已开发票管理】中进行发票上传操作！';
                if(ResultMsg == this.INVOICERECEIVE.INVOICE){
                    msg = '处理完毕，请在【已开发票管理】中进行发票上传操作！'
                }else if(ResultMsg == this.INVOICERECEIVE.RECEIVE){
                    msg = '领用成功！'
                }
                else if(ResultMsg == this.INVOICERECEIVE.DOWNLIMIT){
                    msg = '下载授信额度成功！'
                } else if(ResultMsg == this.INVOICERECEIVE.RETURNLIMIT){
                    msg = '退回授信额度成功！'
                }
                this.$alert(msg, '提示', {
                    showCancelButton:false,
                    showConfirmButton:false,
                    confirmButtonText: '确认',
                    callback: action => {
                        this.closeDialog()
                    }
                    }).then(data=>{
                    },err=>{
                    })

            }
        },
        // 终止
        async stop(){
            let  obj = {
                    "busId": this.busId
                }
            let { data, code, message } = await stopProcess(
                obj
            )
            if(code ==200){
                this.$message.success(data || message)
                this.closeDialog()
            }
        },


        // 保存
        async save(){
            let obj = {
                "approvalUser": this.$store.state.invoice2.invoinceFormStart1.approvalUser,
                "busData": JSON.stringify(this.$store.state.invoice2.busData),
                "busId": this.busId || this.$store.state.invoice2.invoinceFormStart1.busId,
                // "busId": params.busId || this.$store.state.invoice2.invoinceFormStart1.busId,
                "busType": this.busType,
                "createTime": this.$store.state.invoice2.invoinceFormStart1.createTime,
                "description": this.$store.state.invoice2.invoinceFormStart1.description,
                "submit": false
            }

            if(!obj.description && (this.busType === 'FLOW_HZQRDQR' || this.busType === 'FLOW_HZQRDSQ')){
                this.btnLoading = false;
                return this.$message.error('请填写事项说明')
            }
            if(!obj.approvalUser){
                this.btnLoading = false;
                return this.$message.error('请选择即将流向人')
            }
            let { data, code, message } = await saveOrSubmit(
                obj
            )
            if (code == 200) {
                this.closeDialog();
                this.$message.success(message || data)
            }else if(code === '7012'){
                this.msgShow = true;
                        this.messageDialog = data
            }
        },
        // 提交
        async submit(){
            let obj = {
                "approvalUser": this.$store.state.invoice2.invoinceFormStart1.approvalUser,
                "busData": JSON.stringify(this.$store.state.invoice2.busData)  ,
                "busId": this.busId || this.$store.state.invoice2.invoinceFormStart1.busId,
                // "busId": params.busId || this.$store.state.invoice2.invoinceFormStart1.busId,
                "busType": this.busType,
                "createTime": this.$store.state.invoice2.invoinceFormStart1.createTime,
                "description": this.$store.state.invoice2.invoinceFormStart1.description,
                "submit": true
            }
            console.log(obj)
            if(!obj.approvalUser){
                this.btnLoading = false;
                return this.$message.error('请选择即将流向人')
            }
            if(!obj.description && (this.busType === 'FLOW_HZQRDQR' || this.busType === 'FLOW_HZQRDSQ')){
                this.btnLoading = false;
                return this.$message.error('请填写事项说明')
            }
            if(this.$store.state.invoice2.invoinceFormAdvice6.handleResult == 3&&!this.$store.state.invoice2.invoinceFormAdvice6.remark){
                this.btnLoading = false;
                return this.$message.error('请填写事项说明')
            }

            let { data, code, message } = await saveOrSubmit(
                obj
            )
            if (code == 200) {
                this.$message.success(message || data)
                this.closeDialog();
            }else if(code === '7012'){
                this.msgShow = true;
                this.messageDialog = data
            }
        },
                // 关闭弹框
        closeDialog(){
                this.$emit('closeSearch')
                try {
                    // this.closeFather();

                } catch(e) {

                }
        },

        async IsError(){
            console.log(this)
            console.log(this.nodeId)
            if(this.nodeId === 'FLOW_PPLS_SP'){ // 只有审批需要判断
                if( typeof this.$store.state.fpxxlStore.matchAllowError.dqppcyje === 'string'){
                    if(this.$store.state.fpxxlStore.matchAllowError.dqppcyje !== '0' &&  (!this.$store.state.fpxxlStore.matchAllowError.cyjesm || !this.$store.state.fpxxlStore.matchAllowError.yxcyje)){
                        return true;
                    }else{
                        // 肯定有数据了
                        let isContinue =  await  beforeInvoiceMatchFlow(this.busType,this)
                        if(!isContinue)return;
                    }
                }
            }
            return  false;
        }
    },
}
</script>

  <style scoped lang = "scss">
.handleDetail {
    // overflow-y:  auto;
    // overflow-x: hidden;
    // height: calc(100vh);
    .btnList {
        display: flex;
        justify-content: center;
        height: 32px;
        margin-bottom: 35px;
    }
}
</style>
